<template>
  <div class="takephoto">
    <van-nav-bar
      title="人脸录入"
      left-text=""
      left-arrow
      @click-left="onClickLeft"
      fixed
      placeholder
    />
    <!-- <input
      class="upload"
      type="file"
      accept="image/*"
      capture="camera"
      @change="onImageChange"
    />

    <button @click="uploadFace">点击上传人脸</button> -->
    <div class="upload">
      <van-uploader
        v-model="fileList"
        preview-size="120px"
        :max-count="1"
        :after-read="afterRead"
      />

      <van-button type="primary" size="normal" @click="goUploadFace"
        >点击上传</van-button
      >
    </div>
  </div>
</template>

<script>
import ImageCompressor from "js-image-compressor"
import { Toast } from "vant"
export default {
  data() {
    return {
      params: {
        // access_token: "",
        // baseData: "",
      },
      fileList: [],
    }
  },

  methods: {
    goUploadFace() {
      console.log(this.fileList)
      let files = this.fileList[0].file
      let self = this
      return new Promise((resolve, reject) => {
        new ImageCompressor({
          // 图片压缩配置
          file: files,
          quality: 0.6,
          mimeType: "image/jpeg",
          maxWidth: 2000,
          maxHeight: 2000,
          width: 1000,
          height: 1000,
          minWidth: 500,
          minHeight: 500,
          convertSize: Infinity,
          loose: true,
          redressOrientation: true,
          // 压缩前回调
          beforeCompress: function (result) {
            console.log("压缩之前图片尺寸大小: ", result.size)
            console.log("mime 类型: ", result.type)
          },
          // 压缩成功回调
          success: function (result) {
            console.log("压缩结果:", result)
            console.log("压缩之后图片尺寸大小: ", result.size)
            console.log("mime 类型: ", result.type)
            console.log(
              "实际压缩率： ",
              (((this.file.size - result.size) / this.file.size) * 100).toFixed(
                2
              ) + "%"
            )

            resolve(result)
          },
          // 发生错误
          error: function (msg) {
            reject(msg)
            console.error(msg)
          },
        })
      }).then((res) => {
        console.log(res)
        let blob = res
        let reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onloadend = function () {
          let base64data = reader.result
          console.log(base64data)
          let dataBase = base64data.split(",")[1]
          self.params.baseData = dataBase
          self.fileList[0].status = "uploading"
          self.fileList[0].message = "录入中..."
          // 获取access_token
          self.$api.my
            .userFace()
            .then((res) => {
              let obj = JSON.parse(res.data)
              self.params.access_token = obj.access_token
              console.log(self.params.access_token)
            })
            .then((res) => {
              // 发生请求注册人脸
              console.log(self.params)
              self.$api.my.registerUserFace(self.params).then((res) => {
                console.log(res)
                if (res.code == 200) {
                  Toast("人脸录入成功")
                  self.fileList[0].status = "success"
                  self.fileList[0].message = "录入成功"
                }
              })
            })
        }
      })
    },

    // 调用
    async onImageChange(e) {
      //   //   如果用户选择了图片就将图片转化为base64位的格式进行存储和使用
      //  // 第一步：先读取文件
      //   const base = new FileReader()
      //  // console.dir(base)
      //  // 第二步：将需要转化的图片放进去
      //   base.readAsDataURL(e.target.files[0])
      //  // 第三步：获取结果， 因为文件加载需要时间，因此是个异步的过程，需要使用onload去获取读取的结果，读取转化后的结果放在了result属性里了
      // base.onload = () => {
      //   this.baseURL = base.result
      // }
      let that = this
      let file = e.target.files[0]
      console.log(file)
      const base = new FileReader()
      base.readAsDataURL(file)
      base.onload = function () {
        that.params.baseData = base.result.toString().split(",")[1]
      }
    },

    uploadFace() {
      // 获取access_token
      this.$api.my
        .userFace()
        .then((res) => {
          let obj = JSON.parse(res.data)
          this.params.access_token = obj.access_token
          console.log(this.params.access_token)
        })
        .then((res) => {
          // 发生请求注册人脸
          console.log(this.params)
          this.$api.my.registerUserFace(this.params).then((res) => {
            console.log(res)
          })
        })
    },
    // 图片转换成base64
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        let imgResult = ""
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },
    // 压缩图片
    compressImage(file) {
      return new Promise((resolve, reject) => {
        let thumb = ""
        let isLt2M = file.size / 1024 / 1024 < 2

        let img = new Image()
        // 创建一个reader实例
        let reader = new FileReader()

        // 读取拿到的文件
        reader.readAsDataURL(file)
        reader.onload = function (e) {
          // 文件加载成功后去转成Img对象
          img.src = e.target.result
          let content = img.src.slice(img.src.indexOf(",") + 1, img.src.length)

          if (isLt2M) {
            resolve(content)
            return
          }

          img.onload = function () {
            // 创建画布canvas
            let canvas = document.createElement("canvas"),
              context = canvas.getContext("2d")
            // 设置画布的宽高
            let originWidth = this.width, // 此处 this===img
              originHeight = this.height
            // 最大尺寸限制
            let maxWidth = 1024,
              maxHeight = 1024
            // 该图片尺寸
            let targetWidth = originWidth,
              targetHeight = originHeight
            // 该图片宽或高大于最大尺寸限制时
            if (originWidth > maxWidth || originHeight > maxHeight) {
              // 以图片最长边为最大尺寸进去等比例缩放
              if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽
                targetWidth = maxWidth
                targetHeight = Math.round(
                  maxWidth * (originHeight / originWidth)
                )
              } else {
                targetHeight = maxHeight
                targetWidth = Math.round(
                  maxHeight * (originWidth / originHeight)
                )
              }
            }
            // canvas对图片进行缩放
            canvas.width = targetWidth
            canvas.height = targetHeight
            // 清除画布
            context.clearRect(0, 0, targetWidth, targetHeight)
            // 将图片画在画布上
            context.drawImage(img, 0, 0, targetWidth, targetHeight)
            // 转为base64格式
            ;(thumb = canvas.toDataURL("image/jpeg")),
              (thumb = thumb.slice(thumb.indexOf(",") + 1, thumb.length))

            if (img.src.length === 0) {
              reject(false)
            }
            let data = {
              // 原始图片大小
              content,
              // 压缩后图片大小
              thumb,
            }
            console.log("图片大小对比", data)
            resolve(thumb)
          }
        }
      })
    },

    beforeRead(file) {
      console.log(file)
      let that = this
      const base = new FileReader()
      base.readAsDataURL(file)
      console.log(base)
      base.onload = function () {
        that.params.baseData = base.result.toString().split(",")[1]
      }
      this.uploadFace()
    },

    afterRead() {},

    onClickLeft() {
      this.$router.push("/my")
    },
  },
}
</script>

<style lang="less" scoped>
.upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100vw;
  margin: 20px auto;
}
</style>



